/*学院报名统计*/
<template>
  <div class="student-regist-container">
    <div style="height: 30px;">
      <el-breadcrumb style="float: left;" separator="/">
        <el-breadcrumb-item :to="{ path: '/putonghuaExamsCreate' }">
        <span @click="reback()" >{{ $t('mandarin.createExams') }}</span></el-breadcrumb-item>
        <el-breadcrumb-item>{{ $t('mandarin.collegeRegistStatistics') }}</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button style="float:right; padding:0;" type="text" @click="reback()">{{ $t('common.btn.back') }}</el-button>
    </div>
      <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
        <h1 class="condition-title">{{$t('collegeRegistStatistics.collegeStatistics')}}</h1>
        <div class="float-left associated-conditional-input">
            <!-- <KeywordInput
              v-model="queryForm.condition.collegeName"
              :placeholder="$t('collegeRegistStatistics.cleaseCollege')"
              @enter="onSubmit"/> -->
              <el-input
                v-model.trim="queryForm.condition.collegeName"
                :placeholder="$t('collegeRegistStatistics.cleaseCollege')"
                style="width:250px"
                @keyup.enter.native="onSubmit">
                  <i slot="suffix"
                    class="el-icon-search"
                    style="margin-top:10px;cursor:pointer"
                    @click="onSubmit">
                  </i>
              </el-input>
        </div>
        <div class="edu-opertion-bar sub-title">
          <div class="float-right" style="display: flex;">
            <el-button type="primary" @click="exportDerive">{{$t('collegeRegistStatistics.derive')}}</el-button>
          </div>
        </div>
        <edu-table :pagination="false" :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
         
          <edu-table-column :label="$t('collegeRegistStatistics.college')" prop="collegeNameI18n">
            <!-- <template slot-scope="scope">
              {{scope.row.collegeName | collegeAcademyList(options.faculty)}}
            </template> -->
          </edu-table-column>
          <edu-table-column :label="$t('collegeRegistStatistics.numberApplicants')" prop="signedUp"></edu-table-column>
          <edu-table-column :label="$t('collegeRegistStatistics.unsuccessfulApplicants')" prop="notSignedUp">
          </edu-table-column>
          <edu-table-column :label="$t('collegeRegistStatistics.headcount')" prop="totalStudent"></edu-table-column>
          
        </edu-table>
        <el-row type="flex" class="row-bg" justify="end">
          <el-col>
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryForm.pageNum_"
                :page-sizes="[2,20, 40, 80, 100]"
                :page-size="queryForm.pageSize_"
                layout="total, sizes, prev, pager, next, jumper"
                :total="queryForm.total_"
                style="float:right;margin-top:10px"
              ></el-pagination>
          </el-col>
        </el-row>
      </el-card>
      <el-dialog
        :title="$t('collegeRegistStatistics.timeSetting')"
        :visible.sync="dialogVisible"
        width="30%"
        :close-on-click-modal='false'
        :before-close="cancel">
        <el-form ref="collegeRegistStatistics" :rules="rules" :model="collegeRegistStatistics" label-width="80px">
          
          <el-form-item :label="$t('graduate.college')" prop="collegeAcademyList">
            <el-select collapse-tags multiple v-model="collegeRegistStatistics.collegeAcademyList" clearable style="width: 100%">
                <el-option
                    v-for="item in options.faculty"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('collegeRegistStatistics.testTime')" required>
            <el-col :span="11">
              <el-form-item prop="time">
                <el-date-picker style="width: 100%;"
                  v-model="collegeRegistStatistics.time"
                  type="datetime"
                  :picker-options="pickerOptionsStart"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  :placeholder="$t('collegeRegistStatistics.startTime')">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col class="line" :span="1">至</el-col>
            <el-col :span="12">
               <el-form-item prop="timeEnd">
                <el-date-picker style="width: 100%;"
                  v-model="collegeRegistStatistics.timeEnd"
                  type="datetime"
                  :picker-options="pickerOptionsEnd"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  :placeholder="$t('collegeRegistStatistics.endTime')">
                </el-date-picker>
               </el-form-item>
            </el-col>
            <!-- <el-date-picker style="width:100%"
              v-model="collegeRegistStatistics.timeList"
              type="datetimerange"
              :picker-options="pickerOptionsTimeList"
              range-separator="-"
              :start-placeholder="$t('collegeRegistStatistics.startTime')"
              :end-placeholder="$t('collegeRegistStatistics.endTime')">
            </el-date-picker> -->
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel">{{$t('studentsRegist.cancel')}}</el-button>
          <el-button type="primary" @click="reliable">{{$t('studentsRegist.confirm')}}</el-button>
        </span>
      </el-dialog>
      <edu-export-dialog
        :disabled="exportButton"
        :title="$t('message.prompt')"
        ref="downloadRef"
        :data="exportResult">
      </edu-export-dialog>
  </div>
</template>
<script>
import ConditionCard from 'common/src/views/subjectCompetition/component/ConditionCard';
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import subjectCompetitionApi from 'common/src/api/subjectCompetition/subjectCompetition';
export default {
  props: {
    examId: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  components: {
    'mycondition-card': ConditionCard
  },
  data() {
    return{
      dataFormList: {}, //接收路由跳转的数据
      dataForm: {
        
      }, //表格数据
      internship: {
        opinion: ''
      },
      dataList: [],
      exportButton: false,
      collegeRegistStatistics: {
        collegeAcademyList: [],
        timeList: [],
        time: null,
        timeEnd: null
      },
      options: {
        faculty: []
      },
      dialogVisible: false,
      outsideAdvisorId: '',
      curCheckStandard: '',
      curPracticeId: '',
      queryForm: {
        condition: {
          competitionId: '',
          college: '',
          educationTag: Number(this.$store.getters.getProjectId()),
          collegeName: ''
        },
        pageNum_: 1,
        pageSize_: 20,
        total_: 0,
      },
      rules: {
        collegeAcademyList: [
          { required: true, message: this.$t('internship.pleaseSelect'), trigger: 'change' }
        ],
        time: [
          { required: true, message: this.$t('internship.pleaseSelect'), trigger: 'change' }
        ],
        timeEnd: [
          { required: true, message: this.$t('internship.pleaseSelect'), trigger: 'change' }
        ]
      },
      pickerOptionsTimeList: {
        disabledDate: time => {
          // let endDateVal = this.collegeRegistStatistics.timeEnd;
          let signUpEnd = this.examId.signUpEnd;
          if (signUpEnd) {
            // return time.getTime() > endDateVal;
            return new Date(signUpEnd).getTime()> time.getTime()+ 86400000;
          }
        }
      },
      pickerOptionsStart: {
        disabledDate: time => {
          let endDateVal = this.examId.signUpEnd
          let beginDateVal = this.collegeRegistStatistics.timeEnd;
          let list = new Date(endDateVal).getTime()- 86400000;
          let times =  new Date(beginDateVal).getTime();
          if (endDateVal&&beginDateVal) {
            return time.getTime() < list || time.getTime()> times;
          } else if (endDateVal) {
            return time.getTime() < list
          }
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          let beginDateVal = this.examId.signUpEnd
          let endDateVal = this.collegeRegistStatistics.time;
          let list = new Date(endDateVal).getTime();
          let times = new Date(beginDateVal).getTime()- 86400000;
          if (endDateVal&&beginDateVal) {
            return time.getTime() < list || time.getTime()< times;
          } else if (beginDateVal) {
            return time.getTime() < times
          }
        }
      },
      multipleSelection: [],
      tableData: []
    }
  },
  filters: {
    collegeAcademyList(val, array) {
      let str = "";
      for (let item of array) {
        if (val === item.value) {
          str = item.label;
        }
      }
      return str;
    }
  },
  mounted() {
    this.getOptions();
    this.queryForm.condition.competitionId = this.examId.id;
    this.getQueryPractice(this.queryForm);
  },
  created() {
    // console.log(this.examId, 'dfdg');
  },
  methods: {
    onSubmit() {
      this.queryForm.pageNum_ = 1;
      // this.queryForm.collegeName = this.queryForm.condition.collegeNameI18n
      this.getQueryPractice(this.queryForm);
    },
    // 下载
    download (path) {
      downloadfile(path);
    },
    reback() {
      this.$emit('change-exam-create-index')
    },
    getQueryPractice(data) {
      subjectCompetitionApi.getListPageStatistics(data).then(res => {
        if (res.data.list) {
          this.dataList = res.data.list;
          this.queryForm.total_ = res.data.total_;
        }
      });
    },
    // 考试时间设置
    exportTimeSetting() {
      this.dialogVisible = true;
    },
    // 导出
    exportDerive() {
      let obj = {
        "collegeStatisticExcelVOList": this.multipleSelection,
        "condition":{
          educationTag: Number(this.$store.getters.getProjectId()),
          competitionId: this.examId.id,
          collegeName: this.queryForm.condition.collegeName
        }
      }
      subjectCompetitionApi.exportCollegeStatistic(obj).then(res => {
        this.$message({
          type: 'success',
          message: this.$t('studentsRegist.successfully')
        });
      });
    },
    // 轮询直到获取key值的接口返回
    cycleToGetKey() {
      setTimeout(() => {
        let currentIds = [];
        if (this.multipleSelection.length > 0) {
          this.multipleSelection.forEach((element) => {
            currentIds.push(element.id);
          });
        } else {
          currentIds = [];
        }
        graduateStudent.specialist({
          "templateName": this.queryForm.condition.department,
          "baseLevel": this.queryForm.condition.proTitle,
          "isEnabled": this.queryForm.condition.isEnabled,
          "name": this.queryForm.condition.name,
          "sex": this.queryForm.condition.sex,
          "fromSys": this.queryForm.condition.fromSys,
          "category": this.queryForm.condition.category,
          "selectRowIds": currentIds
        }).then(res => {
          if (res.success) {
            this.$refs.downloadRef.close();
            this.exportButton = false;
            this.normalDelayRequest(res.key, res.msg);
          } else {
            this.cycleToGetKey();
          }
        });
      }, 3000);
    },
    // 导出异步
    delayRequest(key, name) {
      setTimeout(() => {
        graduateStudent.downloadGetKey(key, name).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =
              '/api/practiceservice/export/file?path=' +
              res.data.path + '&name=' + name;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    // Normal导出异步
    normalDelayRequest(key, name) {
      setTimeout(() => {
        graduateStudent.downloadGetKey(key).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =
              '/api/practiceservice/export/file?path=' +
              res.data.path + '&name=' + name;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    // 导出
    exportFile(command) {
      // 1、第一步：调该接口，获取key值以及msg中的文件名
      // 2、第二步：将key值放入接口传参
      // 3、第三步：传入path值以及name(msg中的文件名)值，下载文件
      this.exportResult = null;
      this.$refs.downloadRef.open();
      this.exportButton = true;
      this.cycleToGetKey();
      
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = JSON.parse(JSON.stringify(val));
      
      this.multipleSelection.forEach(el => {
        el.collegeName = el.collegeNameI18n
      })
    },
    cancelIntern() {
      if (this.outsideAdvisorId) {
        studentsRegistStudent.exportdownPlan(this.dataFormList.id);
      }
    },
    getOptions() {
      // 筛选条件字典查询
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_YX", 'G_XBIE', "JDJB",]
      };
      queryDic(data).then(res => {
        UTILS.fillSelect(
          {
            faculty: "X_YX",
            degreeType: "JDJB",
            sex:"G_XBIE"
          },
          res.data,
          this.options
        );
        // console.log(this.options);
        
      });
    },
    // 弹框取消
    cancel() {
      this.$refs['collegeRegistStatistics'].resetFields();
      // this.$refs['collegeRegistStatistics'].clearValidate();
      this.collegeRegistStatistics.collegeAcademyList = [];
      // this.collegeRegistStatistics.timeList = [];
      this.collegeRegistStatistics.timeEnd = null;
      this.collegeRegistStatistics.time = null;
      this.dialogVisible = false;
    },
    // 弹框确定
    reliable() {
      this.$refs['collegeRegistStatistics'].validate((valid) => {
          if (valid) {
            // console.log(this.collegeRegistStatistics);
            if (this.collegeRegistStatistics.time > this.collegeRegistStatistics.timeEnd) {
              return this.$message.warning(this.$t('collegeRegistStatistics.beginning'));
            }
            if (this.collegeRegistStatistics.time < this.examId.signUpEnd) {
              return this.$message.warning(this.$t('collegeRegistStatistics.examination'));
            }
            let obj = {
              competitionId: this.examId.id,
              collegeAcademy: this.collegeRegistStatistics.collegeAcademyList.join(),
              examStart: this.collegeRegistStatistics.time,
              examEnd: this.collegeRegistStatistics.timeEnd
            };
            subjectCompetitionApi.postListPageSetTime(obj).then(res => {
              this.$message({
                type: 'success',
                message: this.$t('studentsRegist.successfully')
              });
              this.$refs['collegeRegistStatistics'].resetFields();
              this.dialogVisible = false;
              // this.reback()
            });
            
          }
        });
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val;
      this.queryForm.pageNum_ = 1;
      this.getQueryPractice(this.queryForm);
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val;
      this.getQueryPractice(this.queryForm);
    },
    goBack() {
      this.$store.commit("delete_tabs", this.$route.path);
      this.$router.go(-1);
    },
    // 获取表格数据
    assignment() {
    
    },
  },
}
</script>
<style lang="scss" scoped>
  .student-regist-container ::v-deep {
    .el-breadcrumb__item:last-child ::v-deep {
      .el-breadcrumb__inner {
        color: #606266;
        font-weight: bold;
        cursor: default
      }
    }
    .el-breadcrumb__item ::v-deep {
      .is-link {
        color: #aaa;
        font-weight: unset;
      }
      .is-link:hover {
        color: #409eff;
      }
    }
  }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
.p_cals:hover{
  cursor: pointer;
  color: #409eff;
}
.p_cals{
  color: #aaa
}
.inner-breadcrumb {
    .breadcrumb {
        span {
            font-weight: normal;
            color: #aaa;
        }
        a {
            font-weight: normal;
            color: #aaa;
        }
        a:hover {
            color: #409eff;
        }
        .last {
            font-weight: bold !important;
            cursor: default !important;
        }
        .disable {
            cursor: default !important;
        }
    }
}
.condition-title-p {
    font-weight: 400;
    font-style: normal;
    color: #2b3b4e;
    font-size: 18px;
    margin-bottom: 15px;
}
.base-info-title {
    font-weight: 400;
    font-style: normal;
    font-size: 16px;
    color: #2b3b4e;
}
.table-style-baseinfo {
    background-color: rgba(210, 212, 214, 1);
    box-sizing: border-box;
    border-width: 0.5px;
    border-style: solid;
    border-color: rgba(210, 212, 214, 1);
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    width: 100%;
    font-weight: 401;
    font-style: normal;
    font-size: 14px;
    color: #8896a7;
    margin-bottom: 20px;
}

.table-style-baseinfo td {
    width: 25%;
    background-color: rgba(255, 255, 255, 1);
    border: none;
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    font-weight: 401;
    font-style: normal;
    font-size: 14px;
    color: #2b3b4e;
    height: 32px;
    padding: 0 10px;
}

.table-style-baseinfo .text-right-background-color {
    background-color: #fdfeff4d;
    text-align: right;
}

.text-left-background-none {
    text-align: left;
}
</style>